import { Router } from "vue-router";
import { useUserStore } from "@/store/modules/user.store";
import {
  LOGIN_PAGE,
  NOT_FOUND_PAGE,
  CHOOSE_BRANCH_PAGE,
} from "../routerNames/index";
import { isEmpty } from "lodash-es";
import { usePermissionStore } from "@/store/modules/permission.store";

const BASE_HOME_PATH = CHOOSE_BRANCH_PAGE.URL;
const WHITE_LIST = [LOGIN_PAGE.URL, NOT_FOUND_PAGE.URL];

export const createPermissionGuard = (router: Router) => {

  const userStore = useUserStore();
  router.beforeEach(async (to, from, next) => {
    const token = userStore.getToken;
    const isSessionTimeout = userStore.getSessionTimeout;
    const currentBranch = userStore.currentBranch;
    const toPath = to.path;

    // If the target path is in the whitelist, allow access
    if (WHITE_LIST.includes(toPath)) {
      if (toPath === LOGIN_PAGE.URL && token && !isSessionTimeout) {
        next({ path: BASE_HOME_PATH, replace: true });
      } else {
        next();
      }
      return;
    }

    // If no token is available, handle redirection to login page
    if (!token) {
      if (to.meta.ignoreAuth) {
        next();
      } else {
        const redirectData = {
          path: LOGIN_PAGE.URL,
          replace: true,
          query: { redirect: to.fullPath },
        };
        console.log(`Redirecting to login: ${JSON.stringify(redirectData)}`);
        next(redirectData);
      }
      return;
    }

    if (isEmpty(currentBranch) && toPath !== CHOOSE_BRANCH_PAGE.URL) {
      console.log("choose branch");
      next({ path: CHOOSE_BRANCH_PAGE.URL, replace: true });
      return;
    }

    const permissionStore = usePermissionStore();

    if (!permissionStore.getIsDynamicAddedRoute) {
      const routes = await permissionStore.buildRoutesAction();
      permissionStore.setDynamicAddedRoute(true);

      console.log("====routes");
      console.log(routes);

      routes.forEach((route: any) => {
        router.addRoute(route);
      });
      next({ path: to.fullPath, replace: true });
      return;
    }

    // 处理组件缓存
    const componentName = to.meta?.componentName as string;
    if (componentName && to.meta?.keepAlive) {
      permissionStore.addCachedView(componentName);
    }

    // Handle redirect path from query
    // const redirectPath = from.query.redirect as string;
    // if (redirectPath && redirectPath !== to.fullPath) {
    //   next({ path: decodeURIComponent(redirectPath), replace: true });
    //   return;
    // }

    next();
  });
};
